package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.CDNLogItem;
import cc.eddic.practice.concurrency.CDNLogItemParser;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CDNLogItemParserCxyImpl implements CDNLogItemParser {

    private static final Pattern PATTERN_LOG_LINE = Pattern.compile(
            "(?<clientIP>.+) (?<hitMiss>.+) (?<responseTime>\\d+) \\[(?<timeZone>.+)] \"(?<method>\\w+) (?<url>.+) (?<protocol>\\S+?)\" (?<statusCode>\\d+) (?<trafficSize>\\d+) \"(?<referer>.*?)\" \"(?<userAgent>.*)\"",
            Pattern.UNICODE_CHARACTER_CLASS | Pattern.DOTALL
    );

    private LocalDateTime parseDateTime(String dateTimeString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        return LocalDateTime.parse(dateTimeString, formatter);
    }

    public Optional<CDNLogItem> parse(String line) {
        Matcher matcher = PATTERN_LOG_LINE.matcher(line);
        if (matcher.find()) {
            String clientIP = matcher.group("clientIP");
            String hitMiss = matcher.group("hitMiss");
            long responseTime = Long.parseLong(matcher.group("responseTime"));
            String timeZone = matcher.group("timeZone");
            String method = matcher.group("method");
            String url = matcher.group("url");
            String protocol = matcher.group("protocol");
            int statusCode = Integer.parseInt(matcher.group("statusCode"));
            long trafficSize = Long.parseLong(matcher.group("trafficSize"));
            String referer = matcher.group("referer");
            String userAgent = matcher.group("userAgent");

            Map<String, String> query = new HashMap<>(); // Empty query map

            String path;
            if (url.contains("?")) {
                int index = url.indexOf('?');
                path = url.substring(0, index);
            } else {
                path = url;
            }

            CDNLogItem logItem = new CDNLogItem(clientIP, hitMiss, responseTime, parseDateTime(timeZone),
                    method, path, query, protocol, statusCode, trafficSize, referer, userAgent);

            return Optional.of(logItem);
        }
        return Optional.empty();
    }


}
